package com.store.app.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.BookedBean;
import com.store.app.bean.CouponGoCashBean;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.PayBean;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.stores.LocationService;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.widget.BookedOnlinePopupWindow;
import com.store.app.widget.ProgressWebView;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 惠易定
 */
public class WebViewHYDActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, IOnHttpListener {
    private TextView tv, tv_right;
    private ProgressWebView webView;
    private String title;
    private String urls = "", id = "";
    private LinearLayout btn_back, lin_right;
    private ProgressBar progressBar;
    private SwipeRefreshLayout mSwipeLayout;
    private LinearLayout lin_all;
    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private BookedOnlinePopupWindow bp_online;
    private PopupWindow mPop;
    private final int POST_SUCC = 8;
    private final int POST_FAIL = 9;
    private String errorMsg;
    private NetRequest netRequest;
    private GoToLogin goToLogin;
    private String methodName;//回调惠易定方法
    private String submitGPSInfoMethName = "";
    public static String return_url_wc;
    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case POST_SUCC:
                    dismissProgressDialog();
                    Toast.makeText(WebViewHYDActivity.this, "您的订单已提交，供应商将安排工作人员在24小时内确认订单并协商配送事宜，谢谢合作。", Toast.LENGTH_LONG).show();
                    break;
                case POST_FAIL:
                    dismissProgressDialog();
                    if (!TextUtils.isEmpty(errorMsg)) {
                        Toast.makeText(WebViewHYDActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                    }

                    break;
            }
        }
    };

    public WebViewHYDActivity() {
        super();
    }

    private MyReceiver myReceiver;
    private String sLongitude = "";
    private String sLatitude = "";
    private String sAddress = "";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final LocationService locationService = new LocationService(WebViewHYDActivity.this);
        locationService.registerListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                    Log.i("location", "经度：" + location.getLongitude());
                    Log.i("location", "纬度：" + location.getLatitude());
                    Log.i("location", "地.址：" + location.getAddrStr());
                    sLongitude = location.getLongitude() + "";
                    sLatitude = location.getLatitude() + "";
                    sAddress = location.getAddrStr() + "";
                    locationService.stop();
                }
            }
        });
        locationService.start();


        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_hyd_webview);
        urls = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        Log.v("zyl", "urls:" + urls);
        netRequest = new NetRequest(this);
        goToLogin = new GoToLogin(this);
        findViews();
//        setWebView();

        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new IntentFilter("FINISH"));
        //TODO
		netRequest.requestGetHYDVersion(2, MainActivity.user_token);
        EventBus.getDefault().register(this);
    }

    public void onEvent(EventBusBean busBean) {
        //将扫描后的结果返回给js
        if (busBean.type == 202) {
            String resultCode = busBean.data;
            if (!TextUtils.isEmpty(methodName)) {
                webView.loadUrl("javascript:" + methodName + "('" + resultCode + "')");
            }
        }else if(busBean.type == 211){
            Log.v("zyl", "211加载地址：" + busBean.data);
            if(TextUtils.isEmpty(busBean.data)){
                webView.loadUrl(urls);
            }else{
                webView.loadUrl(busBean.data);
            }
        }
    }
    public void onEvent(PayBean busBean) {
        //微信支付成功
       if(busBean.type == 2){
            Log.v("zyl", "微信支付成功");
           if(!TextUtils.isEmpty(return_url_wc)){
               webView.loadUrl(return_url_wc);
           }
       }else if(busBean.type == -2){
           Log.v("zyl","微信取消");
           if(!TextUtils.isEmpty(return_url_wc)){
               webView.loadUrl(return_url_wc + "?is_success=F");
           }

       }else if(busBean.type == -1){
           if(!TextUtils.isEmpty(return_url_wc)){
               webView.loadUrl(return_url_wc + "?is_success=F");
           }
           Log.v("zyl","微信失败");
       }
    }

    /**
     * 微信支付成功之后发送一个广播过来关闭页面
     */
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("zyl", "接收到广播hydreturn_url_wc:"+return_url_wc);
            EventBus.getDefault().post(new CouponGoCashBean(1));

//            if(!TextUtils.isEmpty(return_url_wc)){
//                webView.loadUrl(return_url_wc);
//            }
        }
    }


    private void setWebView() {
        webView.clearCache(true);
        String ua = webView.getSettings().getUserAgentString();
        Log.v("zyl", "ua:" + ua);

        webView.getSettings().setUserAgentString("store_assistant_app");


        webView.loadUrl(urls);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
//		webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.setWebViewClient(new WebViewClient1() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.v("zyl", "惠易定：" + url);
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    if (url.contains("apk")) {
                        Log.v("zyl", "包含apk");
                        Uri uri = Uri.parse(url);
                        Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                        WebViewHYDActivity.this.startActivity(viewIntent);
                        return true;
                    }
                    return false;
                }
                try {
                    // Otherwise allow the OS to handle things like tel, mailto, etc.
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                }
                return true;
            }
        });
        webView.setWebChromeClient(new WebChromeClient1());
        webView.addJavascriptInterface(new JSInterface(), "jsObj");

    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            Log.v("zyl", "onExecuteSuccess");
            try {
                JSONObject jsonObject = new JSONObject(result);
                String code = jsonObject.getString("code");
                Log.v("zyl", "code:" + code);
                webView.loadUrl("javascript:callback('" + code + "')");
            } catch (Exception e) {

            }
        } else if (requestId == 2) {
            // 2
            try {
                JSONObject jsonObject = new JSONObject(result);
                String hyd_version = jsonObject.getString("hyd_version");
                if (hyd_version.equals("2")) {
                    setWebView();
                } else if (hyd_version.equals("3")) {
                    //

                    JSONArray jsonArray = new JSONArray(jsonObject.getString("cookies"));

                    urls = jsonObject.getString("url");
                    String doMain = jsonObject.getString("cookieDomain");
                    CookieSyncManager.createInstance(WebViewHYDActivity.this);
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                    cookieManager.removeSessionCookie();//移除

                    for (int i = 0; i < jsonArray.length(); i++) {
                        String cookisItem = jsonArray.getString(i);
                        Log.v("zyl", "cookisItem:" + cookisItem);
                        cookieManager.setCookie(doMain, cookisItem);//cookies是在HttpClient中获得的cookie
                    }
                    CookieSyncManager.getInstance().sync();
                    setWebView();
                }
            } catch (Exception e) {

            }

        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (requestId == 1) {
            webView.loadUrl("javascript:callback('')");
        } else if (requestId == 2) {
            ToastUtils.showTextToast(WebViewHYDActivity.this, msg);
            finish();
        }
    }

    final class JSInterface {

        private Handler handler = new Handler();

        //开启扫一扫页面
        @JavascriptInterface
        public void startScanActivity(String tempName) {
            methodName = tempName;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(WebViewHYDActivity.this, HYDCaptureActivity.class);
                    startActivity(intent);
                }
            }, 0);
        }

        @JavascriptInterface
        public void getCode(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    netRequest.requestMobileLoginReg(1);
                    return;
                }
            });
        }

        @JavascriptInterface
        public void getGPSInfo(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    submitGPSInfoMethName = string;
                    Log.v("zyl", "getGPSInfo:" + string);
                    JSONObject jsonObject = new JSONObject();


                    try {
                        jsonObject.put("longitude", sLongitude);
                        jsonObject.put("latitude", sLatitude);
                        jsonObject.put("address", sAddress);
                    } catch (Exception e) {
                    }
                    String data = jsonObject.toString() + "";
                    Log.v("zyl", "data:" + data);
                    webView.loadUrl("javascript:" + submitGPSInfoMethName + "('" + data + "')");
                }
            });
        }

        // 供JS调用
        public void logout(String str) {

        }

        @JavascriptInterface
        public void finishActivity() {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //关闭页面
                    Log.v("zyl", "关闭页面");
                    finish();
                }
            }, 0);
        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(WebViewHYDActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }

    public class WebViewClient1 extends android.webkit.WebViewClient {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
//            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //停止webView的所有操作
            webView.onPause();
            webView.pauseTimers();
            showLoadResult(1);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.startsWith("http")) {
                urls = url;
                //  webView.getSettings().setBlockNetworkImage(false);

            }
        }

    }

    public class WebChromeClient1 extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.v("zyl", "加载进度：" + newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() == View.GONE)
                    progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

    }

    public void onPause() {//继承自Activity
        super.onPause();
        webView.onPause();

        webView.pauseTimers();
        if (isFinishing()) {
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    private void findViews() {
//		lin_right =(LinearLayout) findViewById(R.id.public_ll_right);
//		lin_right.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				finish();
//			}
//		});
//		tv_right= (TextView)findViewById(R.id.public_tv_right);
//		tv_right.setText("关闭");
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无网络
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                showLoadResult(3);
                webView.clearCache(true);
                webView.clearHistory();
                webView.clearFormData();
                webView.loadUrl(urls);
            }
        });
        lin_all = (LinearLayout) findViewById(R.id.lin_all);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setContext(this);

//		tv=(TextView) findViewById(R.id.tvTitle);
//		tv.setText(title);
//		findViewById(R.id.public_ll_return).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
//					webView.goBack();// 返回前一个页面
//				} else {
//					finish();
//				}
//			}
//		});
//		lin_loadfail.setOnClickListener(new OnClickListener() {
//			@o
//			public void onClick(View v) {
//				lin_loadfail.setVisibility(View.GONE);
//				webView.clearCache(true);
//				webView.clearHistory();
//				webView.clearFormData();
//				webView.loadUrl(urls);
//			}
//		});

        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.sw);
        mSwipeLayout.setOnRefreshListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        unregisterReceiver(myReceiver);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        setWebView();
        mSwipeLayout.setRefreshing(false);
    }

    /**
     * 订单提交
     */
    public class PostGoodsInfo extends Thread {
        private int num;
        private String money;
        private BookedBean bean;

        public PostGoodsInfo(int num, String money, BookedBean bean) {
            this.num = num;
            this.money = money;
            this.bean = bean;
        }

        public void run() {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                DecimalFormat df = new DecimalFormat("######0.00");
                double d_maker = Double.parseDouble(bean.getMarket_price()) * num;
                double d_discount = Double.parseDouble(money);
                double free = d_maker - d_discount;

                JSONObject paramstwo = new JSONObject();
                paramstwo.put("goods_id", bean.getGoods_id());
                paramstwo.put("qty", num + "");
                paramstwo.put("goods_unit", bean.getGoods_unit());
                paramstwo.put("sale_price", df.format(d_maker));
                paramstwo.put("total_fee", money);
                paramstwo.put("discount_fee", df.format(free));
                //新增接口
                paramstwo.put("goods_title", bean.getTitle());
                paramstwo.put("goods_pic_info", bean.getPic_info());

                JSONObject paramsone = new JSONObject();
                paramsone.put("desc1", bean.getTitle());
                paramsone.put("item_num", "1");
                paramsone.put("total_fee", money);
                paramsone.put("discount_fee", df.format(free));
                paramsone.put("sale_fee", df.format(d_maker));
                paramsone.put("member_id", MainActivity.member_id);
                paramsone.put("member_type_key", "stores");
                paramsone.put("delivery_address", Stores.address);
                paramsone.put("contact_person", Stores.contact_person);
                paramsone.put("contact_tel", Stores.contact_tel);
                paramsone.put("ps_goods", paramstwo.toString());

                params.add(new BasicNameValuePair("params", paramsone.toString()));
                params.add(new BasicNameValuePair("service", "order.psOrderAdd"));
                params.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                String sign = Submit.genPackageSignUser(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/opsorder");
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Message msg = Message.obtain();
                    msg.what = POST_SUCC;
                    handler.sendMessage(msg);
                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        Message msg = Message.obtain();
                        msg.what = POST_FAIL;
                        errorMsg = obj.getString("error_msg");
                        handler.sendMessage(msg);
                    }
                }
            } catch (Exception e) {
                Message msg = Message.obtain();
                msg.what = POST_FAIL;
                handler.sendMessage(msg);
            }
        }
    }


}
